package com.dy.yunying.biz.controller.raffle;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.dy.yunying.api.req.raffle.RaffleDataReq;
import com.dy.yunying.biz.service.raffle.RaffleDataService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.CommonUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author chengang
 * @Date 2022/11/9
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/lottery/data")
public class RaffleDataController {

	private final RaffleDataService raffleDataService;

	@PostMapping("/list")
	public R list(@RequestBody @Validated RaffleDataReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.failed(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		R check = this.baseCheck(req);
		if (check.getCode() == CommonConstants.FAIL) {
			return check;
		}
		Map<String,Object> result = new HashMap<>();
		result.put("list",raffleDataService.page(req,true));
		result.put("summary",raffleDataService.summary(req));
		JSONObject pageInfo = new JSONObject();
		pageInfo.put("current",req.getCurrent());
		pageInfo.put("size",req.getSize());
		pageInfo.put("total",raffleDataService.count(req));
		result.put("pageInfo", pageInfo);
		return R.ok(result);
	}

	/**
	 * 总数目前在分页接口中返回，待查询性能差时具体考虑
	 * @param req
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/count")
	public R count(@RequestBody @Validated RaffleDataReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.failed(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		R check = this.baseCheck(req);
		if (check.getCode() == CommonConstants.FAIL) {
			return check;
		}
		Map<String,Object> result = new HashMap<>();
		result.put("total",raffleDataService.count(req));
		return R.ok(result);
	}

	private R baseCheck(RaffleDataReq req) {
		if (StringUtils.isNotBlank(req.getActivityId())) {
			String activityId = req.getActivityId();
			if (activityId.trim().length() > 20) {
				return R.failed("活动ID长度不能超过20");
			}
			if (!CommonUtils.isPositiveNumber(activityId)) {
				return R.failed("活动ID不是正整数");
			}
		}
		if (StringUtils.isNotBlank(req.getActivityName())) {
			String activityName = req.getActivityName();
			if (activityName.trim().length() > 200) {
				return R.failed("活动名称长度不能超过200");
			}
		}
		Date sDate = DateUtil.parse(req.getStartTime(),"yyyy-MM-dd");
		Date eDate = DateUtil.parse(req.getEndTime(),"yyyy-MM-dd");
		if (eDate.compareTo(sDate) < 0) {
			return R.failed("结束时间不能小于开始时间");
		}
		return R.ok();
	}

//	@PostMapping("/export")
//	@PreAuthorize("@pms.hasPermission('EXPORT_RAFFLE_ACTIVITY_DATA_BTN')")
//	public void export4RedPack(@RequestBody RaffleDataReq req, HttpServletResponse response) {
//		try {
//
//			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//			response.setCharacterEncoding("utf-8");
//			String fileName = URLEncoder.encode("抽奖活动数据-"+ DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
//			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//			response.setHeader("file-name", fileName);
//			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
//			WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "抽奖活动数据")
//					.head(RaffleDataDetail.class).build();
//
//			excelWriter.write(raffleDataService.page(req,false),writeSheet0);
//			List<Map<String,Object>> summaryList = Lists.newArrayList();
//			Map<String,Object> summaryMap = new HashMap<>();
//			RaffleDataSummary summary = raffleDataService.summary(req);
//			//TODO
//			summaryList.add(summaryMap);
//			excelWriter.write(summaryList,writeSheet0);
//
//			excelWriter.finish();
//		} catch (Exception e) {
//			log.error("导出抽奖活动数据失败：{}", e.getMessage());
//		}
//	}

}
